package org.fireflow2.designer.eclipse.editors;

import org.eclipse.core.runtime.ListenerList;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.SelectionChangedEvent;

public abstract class AbstractSelectionProvider implements ISelectionProvider {

	/**
	 * List of selection change listeners (element type:
	 * <code>ISelectionChangedListener</code>).
	 */
	private ListenerList selectionChangedListeners = new ListenerList();

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.jface.viewers.ISelectionProvider#addSelectionChangedListener(org.eclipse.jface.viewers.ISelectionChangedListener)
	 */
	public void addSelectionChangedListener(ISelectionChangedListener listener) {
		selectionChangedListeners.add(listener);
	}

	/**
	 * @return An array containing all the registered listeners.
	 */
	protected Object[] getSelectionChangedListener() {
		return selectionChangedListeners.getListeners();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.jface.viewers.ISelectionProvider#removeSelectionChangedListener(org.eclipse.jface.viewers.ISelectionChangedListener)
	 */
	public void removeSelectionChangedListener(
			ISelectionChangedListener listener) {
		selectionChangedListeners.remove(listener);
	}

	/**
	 * Notifies any selection changed listeners that the viewer's selection has
	 * changed. Only listeners registered at the time this method is called are
	 * notified.
	 * 
	 * @param event
	 *            a selection changed event
	 * @see ISelectionChangedListener#selectionChanged
	 */
	protected void fireSelectionChanged(final SelectionChangedEvent event) {
		for (Object listener : getSelectionChangedListener()) {
			try {
				((ISelectionChangedListener) listener).selectionChanged(event);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}
